package com.ruoyi.robot.service;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.robot.domain.AnytingLLMBack;
import com.ruoyi.robot.domain.Choices;
import com.ruoyi.robot.domain.DeepSeekBackBody;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;

@Service
public class AnytingLLMService {

    public  String askLocalAnythingLLM(String message) {
        final String API_URL = "http://localhost:3001/api/v1/openai/chat/completions";
        final String API_KEY = "1MTC5JX-TAXMN9Y-GE1W76G-MP81RMN";
            String trueAnswer = "遇到问题,稍后重试!";

//            String requestBody = """
//            {
//                "model": "deepseek-chat",
//                "messages": [
//                    {"role": "user", "content": " """ + question + """
//                    "}
//                ],
//                "temperature": 0.7
//            }
//            """;

            // 请求参数示例（根据实际API文档调整）




        JSONObject message2 = new JSONObject();
        message2.put("role", "user");
        message2.put("content", message);

        JSONArray messages = new JSONArray();
        messages.put(message2);

        JSONObject requestBodyJson = new JSONObject();
        requestBodyJson.put("messages", messages);
        requestBodyJson.put("model", "deepseekworkspace");
        requestBodyJson.put("stream", true);
        requestBodyJson.put("temperature", 0.7);

        String requestBody = requestBodyJson.toString();

            try {
                HttpClient client = HttpClient.newBuilder()
                        .version(HttpClient.Version.HTTP_1_1)
                        .connectTimeout(Duration.ofSeconds(10))
                        .build();

                HttpRequest request = HttpRequest.newBuilder()
                        .uri(URI.create(API_URL))
                        .header("Content-Type", "application/json")
                        .header("Authorization", "Bearer " + API_KEY)
                        .header("accept", "*/*")
                        .POST(HttpRequest.BodyPublishers.ofString(requestBody))
                        .build();

                HttpResponse<String> response = client.send(
                        request, HttpResponse.BodyHandlers.ofString());
//
//                System.out.println("Status Code: " + response.statusCode());
//                System.out.println("Response Body: " + response.body());

                // 解析 JSON 数据
                // 去掉 data: 前缀
                StringBuilder answer = new StringBuilder("");
                String[] split = response.body().split("data: ");
                for (String s : split) {
                    if (s.equals("")){
                        continue;
                    }
                    JSONObject jsonObject = new JSONObject(s);

                    // 获取 choices 数组
                    JSONArray choicesArray = jsonObject.getJSONArray("choices");

                    // 遍历 choices 数组
                    for (int i = 0; i < choicesArray.length(); i++) {
                        JSONObject choice = choicesArray.getJSONObject(i);
                        JSONObject delta = choice.getJSONObject("delta");

                        // 获取 content 字段
                        String content = delta.getString("content");
//                        System.out.println("Content: " + content);
                        answer.append(content);
                    }

//                    AnytingLLMBack deepSeekBackBody = JSON.parseObject(response.body(), AnytingLLMBack.class);
//
//
//                    for (Choices choice : deepSeekBackBody.getChoices()) {
//                        answer.append(choice.getDelta().getContent());
//                    }
                }


                trueAnswer = answer.toString();
                System.out.println("Message Content: " + answer);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return trueAnswer;
    }
}
